package com.meteor.api.feign.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


//import jakarta.servlet.http.HttpServletRequest;


/**
 * @author lynn
 * @date 2023-1-23 10:00
 */
@Configuration
public class FeignRequestConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {

        HttpServletRequest request =  getServletRequest();
        if (null == request) {
            return;
        }

        template.header("Authorization", getHeaders(request));
    }

    private HttpServletRequest getServletRequest() {
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes==null) {
            return null;
        }
        return servletRequestAttributes.getRequest();
//        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    private String getHeaders(HttpServletRequest request) {
        return request.getHeader("Authorization");
    }


}
